package gui.newgui.unassignedplayerspanel;

import gui.newgui.IController;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.Observer;

import table.models.ParticipantsTableModel;
import tournamentData.TournamentData;
import core.Person;
import db.newversion.ArchersDB;

public class UnassignedPlayersController implements IController, Observer {
	UnassignedPlayersPanel window;

	public UnassignedPlayersController(UnassignedPlayersPanel window) {
		this.window = window;
		ArchersDB.getInstance().addObserver(this);
		TournamentData.getInstance().addObserver(this);
	}

	@Override
	public void updateTable() {
		HashMap < Integer, Person > all = ArchersDB.getInstance().getAll();
		Integer [] participants = TournamentData.getInstance().getAllParticipants();

		for (int i = 0; i < participants.length; i++) {
			all.remove(participants [i]);
		}

		if (all.size() > 0) {
			ParticipantsTableModel nonParticipantsTableModel = (ParticipantsTableModel) this.window.getTable().getModel();
			nonParticipantsTableModel.removeData();
			Iterator < Entry < Integer, Person >> iterator = all.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry < Integer, Person > toAdd = iterator.next();
				nonParticipantsTableModel.addRow(new Object [] { toAdd.getKey(), toAdd.getValue().getName(), toAdd.getValue().getSurName(), toAdd.getValue().getNation(),
						toAdd.getValue().getCountry(), toAdd.getValue().getBowCathegory(), toAdd.getValue().getAgeClass(), toAdd.getValue().getClub(), toAdd.getValue().getGender(),
						toAdd.getValue().isLicense(), toAdd.getValue().isCountryRating(), toAdd.getValue().getBirthdate() });
			}

			nonParticipantsTableModel.fireTableDataChanged();
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		this.updateTable();
	}
}
